package org.example.controller;

import cn.hutool.core.io.FileUtil;
import org.example.common.AuthAccess;
import org.example.common.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ip:localhost}")
    String ip;

    @Value("${server.port}")
    String port;

    private static final String ROOT_PATH=System.getProperty("user.dir")+File.separator+"files";  //C:\Users\288\Desktop\Project\springboot\files

    @PostMapping("/upload")
    public Result upload( MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();  //文件的原始名称
        //aa.png
        String mainName = FileUtil.mainName(originalFilename);    //aa
        String extName = FileUtil.extName(originalFilename);   //png
        if (!FileUtil.exist(ROOT_PATH)){
            FileUtil.mkdir(ROOT_PATH);          //如果当前文件的父级目录不存在，就创建
        }
        if (FileUtil.exist(ROOT_PATH +File.separator+ originalFilename)){     //如果说当前上传的文件已经存在，那么这个时候我就要重命名一个文件名称
            originalFilename = System.currentTimeMillis()+ "_" + mainName + "." + extName;
        }
        File saveFile = new File(ROOT_PATH + File.separator+originalFilename);
        file.transferTo(saveFile);  //存储文件到本地的磁盘里面
        String url ="http://"+ip+":"+port+"/file/download/" +originalFilename;
        return Result.success(url);  //返回文件的连接，这个链接就是文件下载的地址，这个下载地址就是我的后台提供出来的

    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {
        response.addHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));  // 预览
        String filePath = ROOT_PATH + File.separator + fileName;
        if(!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);  //数组是一个字节数组，也就说文件的字节流数组
        outputStream.flush();
        outputStream.close();

    }
}
